package com.wust.smartcity.common.util;


import com.wust.smartcity.common.entity.sys.distributedfile.SysDistributedFile;
import com.wust.smartcity.common.exception.BusinessException;
import com.wust.smartcity.common.properties.MinioProperties;
import com.wust.smartcity.common.service.MinioStorageService;
import io.minio.MinioClient;
import io.minio.ServerSideEncryption;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Map;


/**
 * Created by wust on 2019/5/17.
 */

@Component
public class MinioStorageApi {
    static Logger logger = LogManager.getLogger(MinioStorageApi.class);

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;


    /**
     * try {
     * ByteArrayInputStream bais = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));
     * KeyGenerator keyGen = KeyGenerator.getInstance("AES");
     * keyGen.init(256);
     * ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
     * Map<String, String> headerMap = new HashMap<>();
     * headerMap.put("my-custom-data", "foo");
     * minioClient.putObject("mybucket",  "island.jpg", bais,headerMap,sse, "application/octet-stream" );
     * System.out.println("island.jpg is uploaded successfully");
     * } catch(MinioException e) {
     * System.out.println("Error occurred: " + e);
     * }
     *
     * @param objectName  Name of the bucket
     * @param stream      stream to upload
     * @param size        Size of the file
     * @param headerMap   Custom/additional meta data of the object
     * @param sse         Form of server-side encryption ServerSideEncryption
     * @param contentType File content type of the object, user supplied
     * @return
     */
    public SysDistributedFile upload(String objectName, InputStream stream, Long size, Map<String, String> headerMap, ServerSideEncryption sse, String contentType,String fileName,String fileType,String source, MinioStorageService minioStorageService) {
        String bucketName = minioProperties.getBucketName();
        try {
            boolean exist = minioClient.bucketExists(bucketName);
            if(!exist){
                minioClient.makeBucket(bucketName);
            }
        } catch (Exception e){
            logger.error(e);
            throw new BusinessException("上传失败，文件服务器异常。" + e.getMessage());
        }
        return minioStorageService.upload(bucketName,objectName,stream,size,headerMap,sse,contentType,fileName,fileType,source);
    }


    public InputStream download(Long fileId, MinioStorageService minioStorageService) {
        try {
            SysDistributedFile distributedFile = minioStorageService.selectDistributedFileByPrimaryKey(fileId);
            if(distributedFile != null){
                String bucketName = distributedFile.getBucketName();
                String objectName = distributedFile.getObjectName();
                return minioClient.getObject(bucketName, objectName);
            }else{
                throw new BusinessException("对应的文件不存在于文件系统。");
            }
        } catch (Exception e) {
            logger.error("下载文件出错：" + e);
            throw new BusinessException("下载文件异常：" + e.getMessage());
        }
    }


    public void delete(String bucketName, String objectName,MinioStorageService minioStorageService) {
        minioStorageService.delete(bucketName,objectName);
    }
}
